﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BartonExtension;
using System.Threading;

using Model.App;
using Model.Images;
using Model.Weixin;
using Model;

namespace iShangMai
{
    public class JSSDKAccess
    {
        public static string acs_token { get; set; }
        private static int acs_expire_in { get; set; }
        public static string js_ticket { get; set; }
        private static int ticket_expire_in { get; set; }
        private static DateTime acs_refresh_time { get; set; }
        private static DateTime ticket_refresh_time { get; set; }
        public static bool loaded = false;

        static Timer refresher;

        public static void Init()
        {
            Refresh();
            refresher = new Timer((o) =>
            {
                if (acs_expire_in - (DateTime.Now - acs_refresh_time).TotalSeconds < 100)
                {
                    refreshAccessToken();
                }
                if (ticket_expire_in - (DateTime.Now - ticket_refresh_time).TotalSeconds < 100)
                {
                    refreshTicket();
                }
            }, null, 1000 * 60, 1000 * 60);
            loaded = true;
        }

        private static void Refresh()
        {
            refreshAccessToken();
            refreshTicket();
        }

        private static void refreshAccessToken()
        {
            try
            {
                HttpPost acspost = new HttpPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}".FormatWith(Constants.appId, Constants.secret), string.Empty);
                string json_acstoken = acspost.get_sync();
                Dictionary<string, object> acsTokenDic = json_acstoken.FromJson<Dictionary<string, object>>();
                acs_expire_in = acsTokenDic["expires_in"].toInt32().Value;
                acs_token = acsTokenDic["access_token"].ToString();
                acs_refresh_time = DateTime.Now;
            }
            catch (Exception)
            {
                loaded = false;
            }
        }

        private static void refreshTicket()
        {
            try
            {
                HttpPost ticketpost = new HttpPost("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi".FormatWith(acs_token), string.Empty);
                string json_ticket = ticketpost.get_sync();
                Dictionary<string, object> ticketDic = json_ticket.FromJson<Dictionary<string, object>>();
                ticket_expire_in = ticketDic["expires_in"].toInt32().Value;
                js_ticket = ticketDic["ticket"].ToString();
                ticket_refresh_time = DateTime.Now;
            }
            catch (Exception) {
                loaded = false;
            }
        }
    }
}